<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_matching_dist($in_year, $in_month, $in_matching_percent){

	global $vars;
	$db=$vars["db"];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];
	$jp_max_maintain = $vars['jp_max_maintain'];	
	$start_time=mktime(0, 0, 0, $in_month, 1, $in_year);
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, 1, $in_year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month+1, 0, $in_year));
	$maintain_time=mktime(0, 0, 0, $in_month+1, 1, $in_year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	
	$qi = 0;
	$quid = array();
	$t = @mysql_num_rows($r=mysql_query("select distinct(uid) as uid from $db->member_comm where type='m' and year='$in_year' and month='$in_month' and status='confirmed'"));
	for($i=0;$i<$t;$i++){
		$comm = mysql_fetch_assoc($r);
		$uid = $comm['uid'];
		$total_sale = @mysql_result(mysql_query("select sum(total_bv) from $db->purchase where uid='$uid' and no_bv!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
		$total_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$in_year' and month='$in_month'"), 0) or 0;
		$ps = $total_sale + $total_maintain;		$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;				if($user_country=='JP'){			if($ps >= $jp_max_maintain){					$quid[$qi++] = $uid;				}		}else{
			if($ps >= $max_maintain){	
				$quid[$qi++] = $uid;	
			}		}
	}
	if(count($quid)){

		$adjust_matching_percent = $in_matching_percent;
		$percent2 = $adjust_matching_percent;
		$t = @mysql_num_rows($r=mysql_query("select * from $db->member_comm where type='m' and uid in (".implode(',', $quid).") and year='$in_year' and month='$in_month' and status='confirmed'"));
		for($i=0;$i<$t;$i++){
			$comm = mysql_fetch_assoc($r);
			if($adjust_matching_percent > 0){
				$amount2 = round($comm['amount'] * $adjust_matching_percent / 100, 2);
			}else{
				$amount2 = $comm['amount'];
			}
			$sql = "update $db->member_comm set amount2='$amount2', percent2='$percent2' where id='$comm[id]' limit 1";
			if(!mysql_query($sql)){
				$update_err .= "$sql\n";
			}else{
				$member_comm[$comm['uid']] += $amount2;
			}
		}
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $amount){
			$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;			$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;						if($user_country=='JP'){				if($next_month_maintain < $jp_max_maintain){						$maintain_amount = round($amount * $maintenance_percent / 100, 2);						if($maintain_amount + $next_month_maintain > $jp_max_maintain){							$maintain_amount = $jp_max_maintain - $next_month_maintain;						}											$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)						values ('$uid', 'm', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";						if(!mysql_query($sql)){							$insert_main_err.="UID: $uid, comm code: m, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";						}					}else{						$maintain_amount = 0;					}			}else{
				if($next_month_maintain < $max_maintain){	
					$maintain_amount = round($amount * $maintenance_percent / 100, 2);	
					if($maintain_amount + $next_month_maintain > $max_maintain){	
						$maintain_amount = $max_maintain - $next_month_maintain;	
					}	
					$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)	
					values ('$uid', 'm', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";	
					if(!mysql_query($sql)){	
						$insert_main_err.="UID: $uid, comm code: m, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";	
					}	
				}else{	
					$maintain_amount = 0;	
				}			}
			
			$actual_amount = $amount - $total_maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk matching commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			if($maintain_amount > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $maintain_amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
					$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_swrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $maintain_amount;
					@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $mall_point;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
					$update_mw_err.="UID: $uid, amount: $mall_point\n";
				}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_mwrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $mall_point;
					@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}
	}
	
	if($update_err || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($update_err? "\nFailed Updating Matching Bonus:\n\n$update_err" : "").
	($insert_main_error? "Failed Maintenance Calculation:<br />\n<br />\n$insert_main_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>